<template>
  <div class="base-container" id="main">
      <!-- 基本信息 -->
      <t-form ref="form" class="step-form" :colon="true" :data="formData" :rules="rules" labelWidth="180px">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-card class="step-card" size="small" title="基本信息">
              <t-row style="align-items: stretch" :gutter="14">
                <t-col :span="6">
                  <t-form-item label="标准名称" name="projectName">
                    <t-input v-if="this.formData.isOldProject === '1' || this.formData.id" clearable style="width: 390px"
                             v-model="formData.projectName"></t-input>
                    <t-select v-else clearable style="width: 390px" @change="onProjectNameChange"
                              v-model="formData.projectName" :keys="{label:'projectName',value:'projectName'}"
                              :options="mySignOptions">
                    </t-select>
                  </t-form-item>
                  <t-form-item label="标准编号" name="projectNum">
                    <t-input clearable style="width: 390px" v-model="formData.projectNum"></t-input>
                  </t-form-item>
                  <t-form-item label="标准公告号" name="publishNum">
                    <t-input clearable style="width: 390px" v-model="formData.publishNum"></t-input>
                  </t-form-item>
                  <t-form-item label="代替标准号" name="replaceNum">
                    <t-input clearable style="width: 390px" v-model="formData.replaceNum"></t-input>
                  </t-form-item>
                  <t-form-item label="标准性质" name="standardProperty">
                    <t-select clearable style="width: 390px" v-model="formData.standardProperty"
                              :options="dict.type.standard_property">
                    </t-select>
                  </t-form-item>
                  <t-form-item label="标准类别" name="standardCategory">
                    <t-select  clearable style="width: 390px" v-model="formData.standardCategory"
                              :options="dict.type.standard_category">
                    </t-select>
                  </t-form-item>
                  <t-form-item label="标准体系" name="systemId">
                    <t-tree-select clearable filterable style="width: 390px" :treeProps="{ keys: { value: 'id' } }"
                                   v-model="formData.systemId" :data="standardSystemOptions"
                                   placeholder="选择标准体系"></t-tree-select>
                  </t-form-item>
                  <t-form-item help="手输支持自定义创建" label="关键词" name="keyWord">
                    <t-select
                      v-model="formData.keyWord"
                      creatable
                      filterable
                      multiple
                      placeholder="手输支持自定义创建"
                      :options="dict.type.bzh_key_word"
                      style="width: 390px;"
                      @create="createKeyWordOptions"
                    >
                    </t-select>
                  </t-form-item>
                  <t-form-item label="制定或修改" name="formulateType">
                    <t-select clearable style="width: 390px" v-model="formData.formulateType"
                              :options="dict.type.formulate_type">
                    </t-select>
                  </t-form-item>

                </t-col>
                <t-col :span="6">
                  <t-form-item label="联系人姓名" name="linkMan">
                    <t-input style="width: 390px" clearable v-model="formData.linkMan"></t-input>
                  </t-form-item>
                  <t-form-item label="联系人电话" name="linkWay">
                    <t-input style="width: 390px" placeholder="请输入手机号码" clearable v-model="formData.linkWay"></t-input>
                  </t-form-item>
                  <t-form-item ref="reviseNum" v-if="formData.formulateType && formData.formulateType!=='1'"
                               label="被修订标准号" name="reviseNum">
                    <t-input style="width: 390px" clearable v-model="formData.reviseNum"></t-input>
                  </t-form-item>
                  <t-form-item label="主管单位" name="manageDeptId">
                    <t-tree-select clearable filterable style="width: 390px" :treeProps="{ keys: { value: 'id' } }"
                                   v-model="formData.manageDeptId" :data="deptMenuOptions"
                                   placeholder="选择主管单位单位"></t-tree-select>
                  </t-form-item>
                  <t-form-item label="提出时间" name="putDate">
                    <t-date-picker clearable style="width: 390px" v-model="formData.putDate"></t-date-picker>
                  </t-form-item>
                  <t-form-item label="发布时间" name="publishDate">
                    <t-date-picker clearable style="width: 390px" v-model="formData.publishDate"></t-date-picker>
                  </t-form-item>
                  <t-form-item label="实施时间" name="implDate">
                    <t-date-picker clearable style="width: 390px" v-model="formData.implDate"></t-date-picker>
                  </t-form-item>
                  <t-form-item label="批复立项时间" name="lxReplyDate">
                    <t-date-picker clearable style="width: 390px" v-model="formData.lxReplyDate"></t-date-picker>
                  </t-form-item>
                  <t-form-item label="批复报审时间" name="bsReplyDate">
                    <t-date-picker clearable style="width: 390px" v-model="formData.bsReplyDate"></t-date-picker>
                  </t-form-item>
                  <t-form-item label="批复报批时间" name="bpReplyDate">
                    <t-date-picker clearable style="width: 390px" v-model="formData.bpReplyDate"></t-date-picker>
                  </t-form-item>
                </t-col>
              </t-row>
            </t-card>
          </t-col>
        </t-row>

        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item :show-error-message="false" name="draftUnits" label="起草单位" labelAlign="top">
              <standard-company ref="standard-company" v-model="formData.draftUnits"
                                :editOpen="true"></standard-company>
            </t-form-item>
          </t-col>
        </t-row>

        <t-row style="align-items: stretch;margin-bottom: 30px" :gutter="14">
          <t-col :span="12">
            <t-form-item :show-error-message="false" name="draftPersons" label="起草小组成员" labelAlign="top">
              <member-list ref="member-list" :objId="formData.localId" v-model="formData.draftPersons"
                           :editOpen="true"></member-list>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="12">
            <t-form-item required-mark name="fileUpload" label="上传申报相关文件" labelAlign="top" style="margin-bottom: 10px">
              <t-table row-key="id" :columns="projectFileColumns" :data="projectFileData">
                <template #id="{row, rowIndex}">
                  {{ rowIndex + 1 }}
                </template>
                <template #op="{row}">
                  <file-upload accept="application/pdf,image/*" v-model="row.fileIds" :moduleKey="row.moduleKey"
                               :fileList="row.fileLists"
                               :multiple="true" tips="限制pdf、图片">
                    <t-button variant="outline">
                      <t-icon name="cloud-upload" slot="icon"/>
                      点击上传
                    </t-button>
                  </file-upload>
                </template>
                <template #c1="{row}">
                  <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
                  <div v-else>{{ row.c1 }}</div>
                </template>
              </t-table>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row style="margin-top: 20px;text-align: center">
          <t-col :span="12">
            <t-space :size="10">
              <t-button theme="primary" :loading="applyLoading" @click="onSubmit(1)">{{
                  applyLoading ? '提交中...' : '暂存'
                }}
              </t-button>
              <t-button theme="primary" :loading="applyLoading" @click="onSubmit(2)">{{
                  applyLoading ? '提交中...' : '提交'
                }}
              </t-button>
            </t-space>
          </t-col>
        </t-row>

      </t-form>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import {getFiles} from "@/api/common";
import FileUpload from "@/components/FileUpload/index.vue"
import dayjs from "dayjs";
import MemberList from "../../components/member-list.vue";
import standardCompany from "@/pages/bzh/standard/components/standard-company.vue";

export default {
  name: "register-apply",
  components: {
    standardCompany,
    FileUpload,
    MemberList
  },
  dicts: ["formulate_type", "standard_category", "standard_property", "bzh_key_word"],
  // beforeRouteEnter(to, form, next) {
  //   // 动态更改meta值、动态更改activeMenu
  //   const activeMenuDict = {
  //     "1": "/bzh/register/register-national",
  //     "2": "/bzh/register/register-industry",
  //     "3": "/bzh/register/register-place",
  //     "4": "/bzh/register/register-group",
  //     "5": "/bzh/register/register-company",
  //     "6": "/bzh/register/register-guide",
  //   }
  //   to.meta.activeMenu = activeMenuDict[to.query.standardCategory]
  //   next()
  // },
  data() {
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      file_domain: VITE_FILE_DOMAIN,
      localId: null,
      standardSystemOptions: [],
      fileLists: [],
      fileIds: "",
      subBtnLoading: false,
      reviseNumDisable: true,
      active: 1,
      mySignOptions: [],
      projectFileData: [
        {
          id: 1,
          c1: "立项阶段",
          c2: "是",
          moduleKey: "bzhLXJD",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 2,
          c1: "报审阶段",
          c2: "是",
          moduleKey: "bzhBSJD",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 3,
          c1: "报批阶段",
          c2: "是",
          moduleKey: "bzhBPJD",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 4,
          c1: "发布阶段",
          c2: "是",
          moduleKey: "bzhFBJD",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 5,
          c1: "贯标附件",
          c2: "否",
          moduleKey: "bzhGBFJ",
          fileIds: [],
          fileLists: [],
          require: false,
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      deptMenuOptions: [],
      applyLoading: false,
      maxlength: 1000,
      lengthLimitObj: {
        description: 0
      },
      tinymceFlag: 1,
      dayjs,
      formData: {
        fileIds: "",
        projectName: "",
        standardCategory: "",
        standardProperty: "1",
        linkMan: "",
        linkWay: "",
        formulateType: "",
        reviseNum: "",
        consistencyDegree: "",
        internationalStandardNum: "",
        manageDeptId: this.$store.state.user.deptId,
        putDate: "",
        description: "",
        approveStatus: 1,
        draftUnits: [],
        unitName: "",
        draftPersons: [],
        keyWord: [],
        isOldProject: '0',
        localId: null,
        lxReplyDate: "",
        bsReplyDate: "",
        bpReplyDate: "",
      },
      rules: {
        keyWord: [{required: true, validator: (val) => val && val.length, message: "关键词不能为空", type: "error"}],
        // fileIds:[
        //   {
        //     required: true,
        //     message: "标准名称不能为空",
        //   },
        // ],
        projectName: [
          {
            required: true,
            message: "标准名称不能为空",
          },
        ],
        systemId: [
          {
            required: true,
            message: "标准体系不能为空",
          },
        ],
        linkMan: [
          {
            required: true,
            message: "联系人姓名不能为空"
          }
        ],
        linkWay: [
          {
            required: true,
            message: "联系人电话不能为空"
          }
        ],
        putDate: [
          {
            required: true,
            message: "提出时间不能为空"
          }
        ],
        publishDate: [
          {
            required: true,
            message: "发布时间不能为空"
          }
        ],
        implDate: [
          {
            required: true,
            message: "实施时间不能为空"
          }
        ],
        lxReplyDate: [
          {
            required: true,
            message: "批复立项时间不能为空"
          }
        ],
        bsReplyDate: [
          {
            required: true,
            message: "批复报审时间不能为空"
          }
        ],
        bpReplyDate: [
          {
            required: true,
            message: "批复报批时间不能为空"
          }
        ],
        projectNum: [
          {
            required: true,
            message: "标准编号不能为空",
          },
        ],
        standardProperty: [
          {
            required: true,
            message: "标准性质不能为空",
          },
        ],
        standardCategory: [
          {
            required: true,
            message: "标准类别不能为空",
          },
        ],
        formulateType: [
          {
            required: true,
            message: "制定或修改不能为空",
          },
        ],
        reviseNum: [
          {
            required: true,
            message: "被修订标准号不能为空",
          },
        ],
        manageDeptId: [
          {
            required: true,
            message: "主管单位不能为空",
          },
        ],
        // publishDate: [
        //   {
        //     required: true,
        //     message: "提出时间不能为空",
        //   },
        // ],
        // completeDate: [
        //   {
        //     required: true,
        //     message: "发布日期不能为空",
        //   },
        // ],
        // implDate: [
        //   {
        //     required: true,
        //     message: "实施时间不能为空",
        //   },
        // ],
        // consistencyDegree: [
        //   {
        //     required: true,
        //     message: "一致性程度不能为空",
        //   },
        // ],
        // internationalStandardNum: [
        //   {
        //     required: true,
        //     message: "国际标准号不能为空",
        //   },
        // ],
        // internationalStandardName: [
        //   {
        //     required: true,
        //     message: "国际标准名称不能为空",
        //   },
        // ],
        draftUnits: [
          {
            required: true,
            message: "起草单位不能为空",
          },
        ],
        draftPersons: [
          {
            required: true,
            message: "起草小组成员不能为空",
          },
        ],
      },
    }
  },
  mounted() {
    if (this.$route.params.id) {
      const postFile = this.formData.isOldProject === '1' ? 'standard' : 'register'
      const postName = this.formData.isOldProject === '1' ? 'detailById' : 'get'
      this.$api.bzh[postFile][postName](this.$route.params.id).then(response => {
        if (!response.data) {
          return false;
        }
        getFiles(this.$route.params.id).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.projectFileData.forEach((val, index) => {
            this.projectFileData[index].fileLists = files[val.moduleKey] || [];
            this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
          })
        }).catch((e) => {
          this.$message.error(e.toString());
        });
        response.data.keyWord = response.data.keyWord?.split(",").filter(item=> item !== '');
        this.formData = { ...this.formData, ...response.data}

      }
      ).catch(e => {
        this.$message.error(e.toString())
      })
    }
  },
  async created() {
    // if (!this.$route.query.standardCategory) {
    //   this.$message.error("缺少标准类型");
    //   return false;
    // }
    this.formData.isOldProject = this.$route.query.isOldProject || '0';
    if (this.formData.isOldProject !== '1') {
      this.getMySignList();
    }
    // this.formData.standardCategory = this.$route.query.standardCategory;
    this.getDeptTreeSelect(this.$store.state.user.deptId)
    this.getStandardSystemTree()
  },
  methods: {
    onProjectNameChange(val, content) {
      // 剔除id
      this.formData.localId = content.option.id;
      // 根据id 查询详情
      this.$api.bzh.standard.getWaitSignDetail(content.option.id).then(response => {
        if (Object.prototype.hasOwnProperty.call(response.data, "id")) {
          delete response.data.id;
        }
        response.data.keyWord = response.data.keyWord?.split(",").filter(item=> item !== '');
        const {draftPersons} = response.data.reportTrial || []
        // 动态替换多个
        this.formData = { ...this.formData, ...response.data,draftPersons}
        this.formData.projectName = content.option.projectName;

      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getMySignList() {
      return this.$api.bzh.register.myWaitSignList().then(response => {
        this.mySignOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getStandardSystemTree() {
      return this.$api.bzh.standard.standardSystemTree().then(response => {
        this.standardSystemOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    createKeyWordOptions(value) {
      this.dict.type.bzh_key_word.push({
        label: `${value}`,
        value,
      });
    },
    close() {
      this.$tab.closeOpenPage({path: this.$route.meta.activeMenu});
    },
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onSubmit(type) {
      const sysAttMainIds = []
      this.projectFileData.forEach(val => {
        sysAttMainIds.push(...val.fileIds)
      })
      if (type === 1) {
        // 暂存
        this.$refs.form.validate({
          fields: ['projectName']
        }).then((validateResult) => {
          if (validateResult === true) {
            this.applyLoading = true;
            if (!this.formData.id) {
              this.$api.bzh.register[this.formData.isOldProject === '1' ? 'addHistoryOnStandardMy' : 'addOnStandardMy']({
                ...this.formData,
                keyWord: this.formData?.keyWord?.join(","),
                sysAttMainVo: {
                  sysAttMainIds
                }
              }).then(response => {
                sessionStorage.setItem(`${this.taskId}-wcxInnovationId`, response.data.id)
                this.formData.id = response.data.id;
                this.formData.localId = response.data.localId;
                this.applyLoading = false;
                this.$message.success('暂存成功');
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            } else {
              this.$api.bzh.register[this.formData.isOldProject === '1' ? 'updateHistory' : 'update']({
                ...this.formData,
                keyWord: this.formData?.keyWord?.join(","),
                sysAttMainVo: {
                  sysAttMainIds
                }
              }).then(response => {
                this.applyLoading = false;
                this.$message.success('暂存成功');
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            }
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        })

      } else {
        // 提交
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            const isValidate = this.$refs["standard-company"].checkData()
            if (!isValidate) {
              return false
            }
            const isValidate2 = this.projectFileData.every(val => {
              if (val.require && val.fileIds.length <= 0) {
                this.$message.error(`需要上传${val.c1}`);
                return false;
              }
              return true
            })
            if (!isValidate2) {
              return false
            }
            this.applyLoading = true;
            this.$api.bzh.register[this.formData.isOldProject === '1' ? 'submitHistoryOnStandardMy' : 'submitOnStandardMy']({
              ...this.formData,
              keyWord: this.formData?.keyWord?.join(","),
              sysAttMainVo: {
                sysAttMainIds
              }
            }).then(response => {
              this.applyLoading = false;
              this.$message.success('提交成功');
              this.close();
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        });
      }
    }
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>

